package server;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;

import sql.SqlManager;

public class Main {

    public static void startHttpServer () throws Exception {
        SqlManager.init();
        DynamicHandler.init();

        HttpServer server = HttpServer.create(new InetSocketAddress(80), 100);
        HttpHandler staticHandler = new StaticHandler();
        HttpHandler dynamicHandler = new DynamicHandler();
        server.createContext("/", e -> {
            String uriPath = e.getRequestURI().getPath();
            if (uriPath.equals("/query")) {
                dynamicHandler.handle(e);
            } else {
                staticHandler.handle(e);
            }
        });
        server.setExecutor(null);
        server.start();

        System.out.println("Http Server Started");
    }

    public static void startHttpsServer () throws Exception {
        SqlManager.init();
        DynamicHandler.init();

        HttpsServer server = HttpsServer.create(new InetSocketAddress(443), 100);

        KeyStore store = KeyStore.getInstance("JKS");
        store.load(new FileInputStream("key/7411423_tlscript.fun.jks"), "password".toCharArray());
        KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
        factory.init(store, "password".toCharArray());
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(factory.getKeyManagers(), null, null);
        HttpsConfigurator configurator = new HttpsConfigurator(context);
        server.setHttpsConfigurator(configurator);

        HttpHandler staticHandler = new StaticHandler();
        HttpHandler dynamicHandler = new DynamicHandler();
        server.createContext("/", e -> {
            String uriPath = e.getRequestURI().getPath();
            if (uriPath.equals("/query")) {
                dynamicHandler.handle(e);
            } else {
                staticHandler.handle(e);
            }
        });
        server.setExecutor(null);
        server.start();

        System.out.println("Https Server Started");
    }

    public static void main( String[] args ) throws Exception {
        startHttpServer();
        //startHttpsServer();
    }
}
